<h1>Test database</h1>
<script>
/*
var request = window.indexedDB.open("agbase",2);
request.onsuccess = function(event) {
  	var db = event.target.result;
};

request.onupgradeneeded = function(event) {
  	var db = event.target.result;
};
*/

function showDatabases(cb) {
	var request = indexedDB.webkitGetDatabaseNames();
	request.onsuccess = function(event){
		var dblist = event.target.result;
		var res = [];
		for(var i=0;i<dblist.length;i++){
			res.push({databaseid: dblist[i]});
		}
		cb(res);
	};
}

function showTables(dbid,cb) {
	var request = window.indexedDB.open(dbid);
	request.onsuccess = function(event) {
	  	var db = event.target.result;
	  	var res = [];
	  	var tblist = db.objectStoreNames;
		for(var i=0;i<tblist.length;i++){
			res.push({tableid: tblist[i]});
		}
		cb(res);
	};
}

/*
showDatabases(function(data){
	var dbs = data;
	console.log(dbs[1].databaseid);
	showTables(dbs[1].databaseid, function(data){
		console.log(data[0].tableid);
		getAll('mydb','mycollection',function(data){
			console.table(data);
		});
	});
});
*/

function getAll(dbid, tableid, cb) {
	var request = window.indexedDB.open(dbid);
	request.onsuccess = function(event) {
	  	var res = [];
	  	var db = event.target.result;
	  	db.transaction([tableid]).objectStore(tableid).openCursor().onsuccess = function(event) {
		  	var cursor = event.target.result;
		  	if(cursor) {
		  		res.push(cursor.value);
		  		cursor.continue();
		  	} else {
		  		cb(res);
		  	}
	  	}
	}	
}


function openIndexedDBStream(dbid, tableid) {
	var stream = {};
	stream.databaseid = dbid;
	stream.tableid = tableid;
	stream.cursor = undefined;
	stream.next = function(cb) {
		if(!stream.cursor) {
			var request = window.indexedDB.open(stream.databaseid);
			request.onsuccess = function(event) {
			  	var res = [];
			  	var db = event.target.result;
			  	db.transaction([stream.tableid]).objectStore(stream.tableid).openCursor().onsuccess = function(event) {
				  	stream.cursor = event.target.result;
				  	if(stream.cursor) {
				  		cb(stream.cursor.value);
				  	} else {
				  		cb();
				  	}
				};
			}
		} else {
			stream.cursor.continue();
		}
	};
	return stream;
};

if(false) {
var tm = Date.now();
var st1 = openIndexedDBStream('mydb', 'mycollection');

st1.next(function(data) {
	if(data) {
//		console.log(data);
		st1.next();
	} else {
		console.log(Date.now()-tm);
//		console.log('finish');
	}
});
}

var tm1 = Date.now();
getAll('ag155','one',function(data){
	console.log(data);
	console.log(Date.now()-tm1);
});



</script>